<script setup lang="ts" name="systemRole">
import { computed, onMounted, reactive, ref } from 'vue'
import { useThemeConfig } from '@/stores/themeConfig'
import { storeToRefs } from 'pinia'
import { useRoute } from 'vue-router'
import { Filter, Search, Refresh, Delete, FolderAdd } from '@element-plus/icons-vue'
import { Local } from '@/utils/storage'
import { deepClone } from '@/utils/other'
import { isObjectValueEqual } from '@/utils/arrayOperation'

interface Props {
  data: any[]
  columns: TableFormColumn[]
  loading?: boolean
  total?: number
  pagination?: TableFormPagination
  formColumns?: FormColumn[]
  treeProps?: { children: string; hasChildren: string }
  rowKey?: string
}

const props = defineProps<Props>()

const emit = defineEmits(['open-form', 'fetch', 'update:loading'])

// 主题配置
const storesThemeConfig = useThemeConfig()
const { themeConfig } = storeToRefs(storesThemeConfig)
const route = useRoute()
const routeName = String(route.name)
// 分页
const tableFormPagination = ref<TableFormPagination>({
  page: 1,
  pageSize: 10
})
// 表单数据
const params = reactive<TypedAny<any>>({})
// 展开筛选面板
const collapse = Local.get(`${routeName}_collapse`)
const isFilterCollapse = ref(typeof collapse === 'boolean' ? collapse : true)
// 初始值
let objectEqual = {}

// 是否筛选
const isFilter = computed(() => {
  return isObjectValueEqual(params, objectEqual)
})

// col默认参数
const defaultColProps = { xs: 24, sm: 12, md: 6, lg: 6, xl: 4 }

/**
 * 打开表格
 * @param type
 * @param row
 */
const onOpenForm = (type: string, row?: any) => {
  emit('open-form', type, row)
}

/**
 * 筛选显示隐藏
 */
const onFilterCollapse = () => {
  isFilterCollapse.value = !isFilterCollapse.value
  Local.set(`${routeName}_collapse`, isFilterCollapse.value)
}

/**
 * 分页改变
 * @param val
 */
const onHandleSizeChange = (val: number) => {
  tableFormPagination.value.pageSize = val
  emitFetch()
}

/**
 * 分页改变
 * @param val
 */
const onHandleCurrentChange = (val: number) => {
  tableFormPagination.value.page = val
  emitFetch()
}

/**
 * 查询
 */
const emitFetch = () => {
  emit('fetch', params)
}

/**
 * 重置
 */
const onReset = () => {
  props.formColumns?.forEach((v) => {
    if (v.type === 'boolean') {
      params[v.prop] = false
    } else if (v.type === 'string') {
      params[v.prop] = ''
    } else if (v.type === 'select') {
      params[v.prop] = v.multiple ? [] : ''
    } else if (v.type === 'daterange') {
      params[v.prop] = []
    } else {
      params[v.prop] = undefined
    }
  })
  objectEqual = deepClone(params)
}

onMounted(() => {
  if (props.pagination) {
    tableFormPagination.value.page = props.pagination.page
    tableFormPagination.value.pageSize = props.pagination.pageSize
  }
  onReset()
})
</script>
<template>
  <div class="system-role-container layout-padding">
    <el-card shadow="hover" class="mb10">
      <div class="system-user-search flex">
        <div class="flex align-center">
          <el-tooltip
            effect="dark"
            :content="isFilterCollapse ? '收起筛选' : '展开筛选'"
            placement="left"
          >
            <el-button :icon="Filter" circle @click="onFilterCollapse" />
          </el-tooltip>
          <!--          <el-button :icon="Filter" circle @click="onFilterCollapse" />-->
          <span class="ml10">{{ $t(String(route.meta.title)) }}</span>
        </div>
        <div class="ml-auto">
          <el-tooltip v-if="isFilterCollapse" effect="dark" content="清空筛选" placement="left">
            <el-button
              :disabled="isFilter"
              :icon="Delete"
              circle
              :loading="loading"
              @click="onReset"
            />
          </el-tooltip>
          <el-button
            v-if="isFilterCollapse"
            type="primary"
            :icon="Search"
            :loading="loading"
            @click="emitFetch"
          >
            查询
          </el-button>
          <el-button v-else :icon="Refresh" :loading="loading" @click="emitFetch">刷新</el-button>
          <el-button :icon="FolderAdd" type="success" @click="onOpenForm('add')">新增</el-button>
        </div>
      </div>
      <div v-if="isFilterCollapse" class="mt5">
        <el-row :gutter="10">
          <el-col
            v-for="(form, index) in formColumns"
            :key="index"
            v-bind="form.colProps || defaultColProps"
            class="mt5"
          >
            <el-input
              v-if="form.type === 'string'"
              v-model="params[form.prop]"
              v-bind="form.props"
              style="width: 100%"
              clearable
              class="custom-prepend"
            >
              <template #prepend>{{ form.label }}</template>
            </el-input>
            <div
              v-else-if="['date', 'daterange', 'datetime'].includes(form.type)"
              class="flex custom-input"
            >
              <div class="el-input-group__prepend">{{ form.label }}</div>
              <el-date-picker
                v-model="params[form.prop]"
                v-bind="form.props"
                :value-format="form.type === 'datetime' ? 'YYYY-MM-DD hh:mm:ss' : 'YYYY-MM-DD'"
                :type="form.type"
              />
            </div>
            <div v-else-if="form.type === 'select'" class="flex custom-input">
              <div class="el-input-group__prepend">{{ form.label }}</div>
              <el-select v-model="params[form.prop]" v-bind="form.props">
                <el-option
                  v-for="item in form.props?.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <div v-else-if="form.type === 'boolean'" class="flex custom-switch">
              <div class="el-input-group__prepend">{{ form.label }}</div>
              <el-switch v-model="params[form.prop]" v-bind="form.props" />
            </div>
            <div v-else-if="form.type === 'radio'" class="flex custom-switch">
              <div class="el-input-group__prepend">{{ form.label }}</div>
              <el-radio-group v-model="params[form.prop]" v-bind="form.props">
                <el-radio
                  v-for="(item, index) in form.props?.options"
                  :key="index"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
    <div class="pa10 layout-padding-auto layout-padding-view">
      <el-table
        v-loading="loading"
        :data="data"
        :row-key="rowKey"
        :tree-props="treeProps"
        style="width: 100%"
      >
        <slot name="column" />
      </el-table>
      <el-pagination
        v-model:current-page="tableFormPagination.page"
        v-model:page-size="tableFormPagination.pageSize"
        :small="themeConfig.globalComponentSize === 'small'"
        @size-change="onHandleSizeChange"
        @current-change="onHandleCurrentChange"
        :page-sizes="[10, 20, 30]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="mt10"
      />
    </div>
  </div>
</template>
